﻿namespace JobButenko.Models.BusinessLogicLayer
{
    using System.Linq;
    using System.Web;

    public class CandidateRepository
    {
        private readonly JobDataContext dataContext;

        public CandidateRepository(JobDataContext dataContext)
        {
            this.dataContext = dataContext;
        }

        public void CreateCandidate(Candidate candidate)
        {
            var dataManager = new DataManager();
            var user = dataManager.User.GetDbUser(HttpContext.Current.User.Identity.Name);
            var newCandidate = new Candidate
                                   {
                                       UserId = user.UserId,
                                       BirthDay = candidate.BirthDay,
                                       Email = user.Email,
                                       Phone = candidate.Phone,
                                       Name = candidate.Name,
                                       Surname = candidate.Surname,
                                       Info = candidate.Info
                                   };
            this.dataContext.Candidates.InsertOnSubmit(newCandidate);
            this.dataContext.SubmitChanges();
        }

        public Candidate GetCandidateFromUserName(string userName)
        {
            return this.dataContext.Candidates.SingleOrDefault(c => c.User.UserName.Equals(userName));
        }

        public Candidate GetCandidateFromId(int id)
        {
            return this.dataContext.Candidates.SingleOrDefault(c => c.CandidateId.Equals(id));
        }

        public void UpdateCandidateDoc(int resumeDocId, string userName)
        {
            var candidate = this.GetCandidateFromUserName(userName);

            candidate.ResumeDocId = resumeDocId;

            this.dataContext.SubmitChanges();
        }

        public void DeleteCandidateDoc(int candidateId)
        {
            var candidateDb = this.GetCandidateFromId(candidateId);

            candidateDb.ResumeDocId = null;

            this.dataContext.SubmitChanges();
        }

        public Candidate GetCandidateFromResDocId(int id)
        {
            return this.dataContext.Candidates.SingleOrDefault(c => c.ResumeDocId.Equals(id));
        }
    }
}